﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.DeviceEntity.Model;
using KingRoad.EPM.Web.Areas.Device.Models;

using DotNet.Model.MyEntity;
using DotNet.Service;
using DotNet.Utilities;
using KingRoad.EPM.DeviceBLL.UIRules;
using System.Dynamic;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Text;
using NPOI.SS.Util;
using System.IO;

namespace KingRoad.EPM.Web.Areas.Device.Controllers
{
    public class VehicleflowController : BaseController
    {

        /// <summary>
        /// 获取组织机构
        /// </summary>
        /// <returns></returns>
        public JsonResult GetVehicleOrgJson()
        {
            DotNet.Utilities.BaseUserInfo info = UserService.CurrUserInfo;
            string url = Request.QueryString["url"];
            List<Base_Org> list = ServiceManager.Instance.OrganizeService.GetOrgChild(info.DepartmentId.ToString()) as List<Base_Org>;
            List<treeNodes> treenodes = new List<treeNodes>();
            int i = 0;
            foreach (Base_Org tInfo in list)
            {
                if (tInfo.DeletionStateCode != 1)
                {
                    treeNodes node = new treeNodes();
                    node.id = tInfo.Id.ToString();
                    node.pId = tInfo.ParentId.ToString();
                    node.name = tInfo.FullName;
                    if (tInfo.Bank == "Company")
                        node.iconSkin = "iCandyCompany";
                    if (tInfo.Bank == "Department")
                        node.iconSkin = "iCandyDuty";
                    node.target = "ajax";
                    if (i == 0)
                    {
                        node.url = url;// HttpUtility.UrlEncode(info.Name, Encoding.GetEncoding("UTF-8")); 
                    }
                    else
                    {
                        node.url = url + "?roadId=" + tInfo.Id;// HttpUtility.UrlEncode(info.Name, Encoding.GetEncoding("UTF-8")); 
                    }

                    treenodes.Add(node);
                    i++;
                    //深入循环
                    List<BllRoadwayInfo> brlist = BllRoadwayUIRule.GetEntityListBySql(" placid = '" + tInfo.Id.ToString() + "'");
                    if (brlist.Count > 0)
                    {
                        foreach (BllRoadwayInfo brinfo in brlist)
                        {
                            treeNodes node1 = new treeNodes();
                            node1.id = brinfo.Id.ToString();
                            node1.pId = brinfo.PlacId.ToString();
                            node1.name = brinfo.RName;

                            node1.iconSkin = "iCandyCompany";

                            node1.target = "ajax";
                            node1.url = url + "?roadId=" + brinfo.Id;// HttpUtility.UrlEncode(info.Name, Encoding.GetEncoding("UTF-8")); 
                            treenodes.Add(node1);
                        }
                    }
                }
            }
            return Json(treenodes, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Index()
        {

            return View();
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="placId">车道id</param>
        /// <returns></returns>
        public ActionResult List(string roadId)
        {
            if (roadId == null)
            {
                roadId = UserService.CurrUserInfo.DepartmentId.ToString();
            }
            ViewBag.roadId = roadId;
            //Base_Organize oInfo = ServiceManager.Instance.OrganizeService.GetOrganizeEntityById(placId);
            //ViewBag.danwei = oInfo.FullName;
            string sql = "";
            if (roadId != null)
            {
                if (roadId.Length > 8)
                {
                    List<Base_Org> list = ServiceManager.Instance.OrganizeService.GetOrgChild(roadId) as List<Base_Org>;
                    foreach (var item in list)
                    {
                        var bri = BllRoadwayUIRule.GetEntityListBySql(" placId = '" + item.Id + "'");
                        foreach (var li in bri)
                        {
                            sql += " roadId = " + li.Id + " or";
                        }
                    }
                    if (sql.Length > 2)
                    {
                        sql = sql.Substring(0, sql.Length - 2);
                    }
                    else
                    {
                        sql = " roadId < 0";
                    }


                }
                else
                {
                    sql = " roadId=" + roadId;
                }

            }

            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var rlist = BllVehicleflowUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "ReportTime", out totalRecord, sql, " desc", "");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View(new VehicleflowModel { list = rlist });
        }

        /// <summary>
        /// 列表(分页提交)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SplitPage()
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            ViewBag.iput_timestart = Request.Form["iput_timestart"];
            ViewBag.iput_timeend = Request.Form["iput_timeend"];
            ViewBag.roadId = Request.Form["input_roadId"];
            ViewBag.iput_Numb = Request.Form["iput_Numb"];

            ViewBag.sel_shour = Request.Form["sel_shour"];
            ViewBag.sel_sminute = Request.Form["sel_sminute"];
            ViewBag.sel_ehour = Request.Form["sel_ehour"];
            ViewBag.sel_eminute = Request.Form["sel_eminute"];

            if (ViewBag.sel_shour == "")
            {
                ViewBag.sel_shour = 0;
            }
            if (ViewBag.sel_sminute == "")
            {
                ViewBag.sel_sminute = 0;
            }
            if (ViewBag.sel_ehour == "")
            {
                ViewBag.sel_ehour = 23;
            }
            if (ViewBag.sel_eminute == "")
            {
                ViewBag.sel_eminute = 59;
            }
            string sql = " 1=1 ";
            if (ViewBag.roadId != "")
            {
                if (ViewBag.roadId.Length > 8)
                {
                    string sq = " and ( ";
                    List<Base_Org> list = ServiceManager.Instance.OrganizeService.GetOrgChild(ViewBag.roadId) as List<Base_Org>;
                    foreach (var item in list)
                    {
                        var bri = BllRoadwayUIRule.GetEntityListBySql(" placId = '" + item.Id + "'");
                        foreach (var li in bri)
                        {
                            sq += " roadId = " + li.Id + " or";
                        }
                    }
                    if (sq.Length > 8)
                    {
                        sq = sq.Substring(0, sq.Length - 2);
                    }
                    else
                    {
                        sq += " roadId < 0 ";
                    }
                    sql += sq + " ) ";

                }
                else
                {
                    sql += " and RoadId = '" + ViewBag.roadId + "' ";
                }
            }

            if (ViewBag.iput_timestart != "")
                sql += " and ReportTime >= '" + Convert.ToDateTime(ViewBag.iput_timestart + " " + ViewBag.sel_shour + ":" + ViewBag.sel_sminute + ":00").ToString("yyyy-MM-dd HH:mm:ss") + "' ";
            if (ViewBag.iput_timeend != "")
                sql += " and ReportTime <= '" + Convert.ToDateTime(ViewBag.iput_timeend + " " + ViewBag.sel_ehour + ":" + ViewBag.sel_eminute + ":59").ToString("yyyy-MM-dd HH:mm:ss") + "' ";
            if (ViewBag.iput_Numb != "")
                sql += " and Numb = " + ViewBag.iput_Numb;


            var rlist = BllVehicleflowUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "ReportTime", out totalRecord, sql, " desc", "");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("List", new VehicleflowModel { list = rlist });
        }


        #region 车流量统计报表

        public ActionResult IndexTotal()
        {

            return View();
        }
        /// <summary>
        /// 车流量统计列表
        /// </summary>
        /// <param name="placId">车道id</param>
        /// <returns></returns>
        public ActionResult ListTotal(string roadId)
        {
            if (roadId == null)
            {
                roadId = UserService.CurrUserInfo.DepartmentId.ToString();
            }
            ViewBag.roadId = roadId;

            ViewBag.iput_timestart = DateTime.Now.ToString("yyyy-MM") + "-01 ";
            ViewBag.iput_timeend = DateTime.Now.ToString("yyyy-MM-dd");
           
            

            string sql = " ReportTime between '" + ViewBag.iput_timestart + " 0:00:00' and '" + ViewBag.iput_timeend + " 23:59:59'";
            if (roadId != null)
            {
                string sq = " and (";
                if (roadId.Length > 8)
                {
                    List<Base_Org> list = ServiceManager.Instance.OrganizeService.GetOrgChild(roadId) as List<Base_Org>;
                    foreach (var item in list)
                    {
                        var bri = BllRoadwayUIRule.GetEntityListBySql(" placId = '" + item.Id + "'");
                        foreach (var li in bri)
                        {
                            sq += " roadId = " + li.Id + " or";
                        }
                    }
                    if (sq.Length > 8)
                    {
                        sq = sq.Substring(0, sq.Length - 2);
                    }
                    else
                    {
                        sq += " roadId < 0";
                    }
                    sql += sq + " ) ";
                }
                else
                {
                    sql += " and roadId=" + roadId;
                }
               
            }

            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var rlist = BllVehicleflowUIRule.GetTotalEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "RoadId,Numb", out totalRecord, sql, " asc", "");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View(new VehicleflowModel { list = rlist });
        }

        /// <summary>
        /// 列表(分页提交)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult TotalSplitPage()
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            ViewBag.iput_timestart = Request.Form["iput_timestart"];
            ViewBag.iput_timeend = Request.Form["iput_timeend"];
            ViewBag.roadId = Request.Form["input_roadId"];
            ViewBag.sel_shour = Request.Form["sel_shour"];
            ViewBag.sel_sminute = Request.Form["sel_sminute"];
            ViewBag.sel_ehour = Request.Form["sel_ehour"];
            ViewBag.sel_eminute = Request.Form["sel_eminute"];

            string sql = " 1=1 ";
            if (ViewBag.iput_timestart != "")
                sql += " and ReportTime >= '" + Convert.ToDateTime(ViewBag.iput_timestart + " " + ViewBag.sel_shour + ":" + ViewBag.sel_sminute + ":00").ToString("yyyy-MM-dd HH:mm:ss") + "' ";
            if (ViewBag.iput_timeend != "")
                sql += " and ReportTime <= '" + Convert.ToDateTime(ViewBag.iput_timeend + " " + ViewBag.sel_ehour + ":" + ViewBag.sel_eminute + ":59").ToString("yyyy-MM-dd HH:mm:ss") + "' ";
            if (ViewBag.roadId != "")
            {
                string sq = " and (";
                if (ViewBag.roadId.Length > 8)
                {
                    List<Base_Org> list = ServiceManager.Instance.OrganizeService.GetOrgChild(ViewBag.roadId) as List<Base_Org>;
                    foreach (var item in list)
                    {
                        var bri = BllRoadwayUIRule.GetEntityListBySql(" placId = '" + item.Id + "'");
                        foreach (var li in bri)
                        {
                            sq += " roadId = " + li.Id + " or";
                        }
                    }
                    if (sq.Length > 8)
                    {
                        sq = sq.Substring(0, sq.Length - 2);
                    }
                    else
                    {
                        sq += " roadId < 0";
                    }
                    sql += sq + " ) ";
                }
                else
                {
                    sql += " and RoadId = '" + ViewBag.roadId + "' ";
                }
            }
               

            var rlist = BllVehicleflowUIRule.GetTotalEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "RoadId,Numb", out totalRecord, sql, " asc", "");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("ListTotal", new VehicleflowModel { list = rlist });
        }

        #endregion


        /// <summary>
        /// Excel导出
        /// </summary>
        /// <returns></returns>
        public FileResult Excel(string PlacId, string danwei)
        {
            //获取list数据           
            var list = BllRoadwayUIRule.GetEntityListBySql(" PlacId=" + PlacId);
            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            //列宽度

            sheet1.SetColumnWidth(0, 8 * 256);
            sheet1.SetColumnWidth(1, 20 * 256);
            sheet1.SetColumnWidth(2, 20 * 256);
            sheet1.SetColumnWidth(3, 12 * 256);
            sheet1.SetColumnWidth(4, 12 * 256);
            //设置第一行
            IRow row0 = sheet1.CreateRow(0);
            //行高
            row0.Height = 30 * 20;
            //合并单元格
            sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 4));
            //创建单元格
            CreateCell(row0, 0, Getcellstyle(book, "center", false, 14, 300), danwei + "车道信息");


            //给sheet1添加第行的头部标题
            IRow row2 = sheet1.CreateRow(1);
            //行高
            row2.Height = 25 * 20;
            CreateCell(row2, 0, Getcellstyle(book, "center", true, 11, 600), "序号");
            CreateCell(row2, 1, Getcellstyle(book, "center", true, 11, 600), "车道名称");
            CreateCell(row2, 2, Getcellstyle(book, "center", true, 11, 600), "车道编号");
            CreateCell(row2, 3, Getcellstyle(book, "center", true, 11, 600), "经度");
            CreateCell(row2, 4, Getcellstyle(book, "center", true, 11, 600), "纬度");

            //将数据逐步写入sheet1各个行
            for (int i = 0; i < list.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 2);
                CreateCell(rowtemp, 0, Getcellstyle(book), (i + 1).ToString());
                CreateCell(rowtemp, 1, Getcellstyle(book), list[i].RName);
                CreateCell(rowtemp, 2, Getcellstyle(book), list[i].Code);
                CreateCell(rowtemp, 3, Getcellstyle(book), list[i].Lon.ToString());
                CreateCell(rowtemp, 4, Getcellstyle(book), list[i].Lat.ToString());
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            string fileName = HttpUtility.UrlEncode("车道信息.xls", Encoding.GetEncoding("UTF-8"));
            return File(ms, "application/vnd.ms-excel", fileName);

        }
    }
}
